package algo;

import java.util.HashMap;
import java.util.Map;

public class LongestSubstringWithAtMostKDisChars_340 {
    public static void main(String[] args) {

        System.out.println(LengthOfLongestSubstringKDistinct("ceeab", 4));
        System.out.println(LengthOfLongestSubstringKDistinct("abac",2));
    }

    public static int LengthOfLongestSubstringKDistinct(String s, int k) {
        int res = 0;
        int left = 0;
        int num = 0;
        Map<Character, Integer> map = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            int cnt = map.getOrDefault(s.charAt(i), 0);
            if (cnt < 1) num++;
            cnt++;
            map.put(s.charAt(i), cnt);
            if (num <= k) res = Math.max(res, i - left + 1);
            while (num > k) {
                char l = s.charAt(left++);
                int lcnt = map.get(l);
                if (--lcnt < 1) num--;
                map.put(l, lcnt);
            }

        }

        return res;
    }
}
